﻿using log4net.Appender;
using log4net.Core;
using log4net.Filter;
using log4net.Layout;

namespace Ping.Server
{
	public sealed class CustomAppender
		: AppenderSkeleton
	{
		private readonly ConsoleAppender _console;
		private readonly FileAppender _file;
		private readonly SmtpAppender _smtp;

		public CustomAppender()
		{
			_console = new ConsoleAppender();
			_console.AddFilter(new LevelRangeFilter {AcceptOnMatch = true, LevelMin = Level.Info, LevelMax = Level.Fatal});

			_file = new FileAppender();

			_smtp = new SmtpAppender();
			_smtp.AddFilter(new LevelRangeFilter {AcceptOnMatch = true, LevelMin = Level.Error, LevelMax = Level.Fatal});
		}

		public override ILayout Layout
		{
			get { return base.Layout; }
			set
			{
				base.Layout = value;
				_console.Layout = value;
				_file.Layout = value;
				_smtp.Layout = value;

				if (value is PatternLayout)
					((PatternLayout)value).ActivateOptions();
				_file.ActivateOptions();
			}
		}

		public string File
		{
			get { return _file.File; }
			set { _file.File = value; }
		}

		protected override void Append(LoggingEvent loggingEvent)
		{
			_console.DoAppend(loggingEvent);
			_file.DoAppend(loggingEvent);
			_smtp.DoAppend(loggingEvent);
		}
	}
}